package com.example.demo.untils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import ws.schild.jave.MultimediaObject;

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;


public class RtspCheckerUtils {
    public static boolean checkRtspStream(String rtspUrl) {
        try {
            if(StringUtils.isEmpty(rtspUrl)){
                return  false;
            }
            // 解析RTSP URL
            String noPrefix = rtspUrl.substring(7); // 去掉 "rtsp://"
            String host;
            int port;
            String path;

            // 分离主机端口和路径
            int firstSlash = noPrefix.indexOf('/');
            if (firstSlash == -1) {
                host = noPrefix;
                path = "/";
            } else {
                host = noPrefix.substring(0, firstSlash);
                path = noPrefix.substring(firstSlash);
            }

            // 处理端口号
            int colonIndex = host.indexOf(':');
            if (colonIndex != -1) {
                port = Integer.parseInt(host.substring(colonIndex + 1));
                host = host.substring(0, colonIndex);
            } else {
                port = 554; // 默认RTSP端口
            }

            // 建立Socket连接
            try (Socket socket = new Socket(host, port);
                 PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                 BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

                // 设置超时（毫秒）
                socket.setSoTimeout(3000);

                // 构建RTSP DESCRIBE请求
                out.println("DESCRIBE " + rtspUrl + " RTSP/1.0");
                out.println("CSeq: 1");
                out.println("User-Agent: Java RTSP Checker");
                out.println("Accept: application/sdp");
                out.println(); // 空行结束请求头
                out.flush();

                // 读取响应状态行
                String response = in.readLine();
                if (response == null) {
                    System.err.println("错误: 未收到服务器响应");
                    return false;
                }

                // 检查响应码
                if (response.contains("200 OK")) {
                    System.out.println("RTSP流正常: " + response);
                    return true;
                } else {
                    System.err.println("RTSP错误响应: " + response);

                    // 读取更多错误信息
                    StringBuilder errorDetails = new StringBuilder();
                    String line;
                    while ((line = in.readLine()) != null && !line.isEmpty()) {
                        errorDetails.append(line).append("\n");
                    }
                    System.err.println("错误详情:\n" + errorDetails);
                }
            }
        } catch (SocketTimeoutException e) {
            System.err.println("错误: 连接超时 - " + e.getMessage());
        } catch (ConnectException e) {
            System.err.println("错误: 连接被拒绝 - 请检查服务器是否运行在 " + rtspUrl);
        } catch (IOException e) {
            System.err.println("IO错误: " + e.getClass().getSimpleName() + " - " + e.getMessage());
        } catch (Exception e) {
            System.err.println("未知错误: " + e.getMessage());
        }
        return false;
    }

    public static void main(String[] args) throws IOException, InterruptedException {
//        String rtspUrl = "rtsp://example.com/live/stream";
//        boolean isAlive = checkRtspStream(rtspUrl);
//        System.out.println("流状态: " + (isAlive ? "正常" : "异常"));

       // RecordingMp4Utils.mergeTSFiles("D:\\jdk18\\hls2Record\\7","D:\\jdk18\\hls2Record\\7\\merged.mp4");


//        String filePath = "D:\\jdk18\\hls2Record\\7\\merged.mp4";
//        try {
//            MultimediaObject instance = new MultimediaObject(new File(filePath));
//            Long  miss= instance.getInfo().getDuration(); // 返回毫秒数
//            System.out.println(miss/1000);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        Map<String,String> map=new HashMap();
        map.put("macAddress","41515");
        map.put("businessId","8");
        map.put("businessType","1");
        map.put("recordingStatus","1");
        sendPostRequest( map);
    }


    public static void sendPostRequest( Map<String,String> map) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String params = mapper.writeValueAsString(map);
            URL url = new URL("http://cs.xmmillions.com:18082/client/uploadRecordingStatus");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("User-Agent", "Java HttpURLConnection");
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            connection.setDoOutput(true);

            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                wr.writeBytes(params);
                wr.flush();
            }

            int responseCode = connection.getResponseCode();
            System.out.println("Response Code : " + responseCode);
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                System.out.println("Response: " + response.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}